package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * PingWest  网站解析
 * @author Chase
 *
 */
public class PingwestNewsAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://www.pingwest.com/[a-z0-9\\-]*/"
	};


	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String url=urlMeta.getUrl();
		/*
		 * 网站源码
		 */
		String htmltxt=urlMeta.getHtml();



		String title=null;
		String content=null;
		String author = null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);

		/*
		 * 标题
		 */
		title=doc.select("title").text();

		/*
		 * 时间
		 */
		date=DateUtils.matchDate(doc.select("span.post-time").text());
		if(date == null){
			date=DateUtils.matchDate(doc.select(".metadata").text());
		}


		/*
		 * 内容
		 */
		author = doc.select("span.name").text();
		content=HtmlCleaner.getContentHtml(url,doc.select("div.post-con"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select(".content p"));
		}
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div.inner1"));
		}
		title=StringUtils.substringBefore(title, "|");
		if(StringUtils.isBlank(title)){
			title=doc.select("h1.article-title").text();
			if(StringUtils.isBlank(title)){
				title=doc.select("h1#topic_title").text();
			}
		}
		/*
		 * 链接
		 */
		news.setUrl(url);

		/*
		 * 来源
		 */
		news.setTitle(title);
		news.setAuthor(author);
		news.setContent(content);
		news.setDate(date);
		return news;
	}

	public static void main(String[] args) {
		PingwestNewsAnalyse analyse=new PingwestNewsAnalyse();
		String url="http://www.pingwest.com/feed/";
		url=UrlArgumentTop.FromatUrl(url);
		System.err.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}


	
	public boolean isNeedUpdate(){
		return false;
	}
}
